$(function () {
    var loadGif = '<img src="../../statics/plugins/layer/skin/default/loading-1.gif" style="margin-right:10px;"/>正在加载,请稍候……';
    $("#jqGrid").jqGrid({
        url: baseURL + 'subject/list',
        datatype: "json",
        colModel: [
			{ label: 'dataId',hidden:true, name: 'dataId', index: 'data_id', width: 50, key: true },
			{ label: '经营主体名称', name: 'name', width: 150 }, 					 			
			{ label: '主体类型', name: 'identityName',width: 120 },
			{ label: '联系人', name: 'linkMan',width: 100 }, 			
			{ label: '联系电话', name: 'linkTel',width: 100 }, 			
			{ label: '地市', name: 'cityName',width: 80 }, 
			{ label: '区县', name: 'countyName',width: 80 }, 
			{ label: '乡镇', name: 'villagesName',width: 80 }, 
			{ label: '村组', name: 'hamletName',width: 80 }, 
			{ label: '积分', name: 'integral',width: 80 , formatter: function(value, options, row){
                    return value == null ? 0 : value;
			}},
			{ label: '状态', name: 'status', width: 60, formatter: function(value, options, row){
				return value === 0 ? 
					'<span class="label label-danger">禁用</span>' : 
					'<span class="label label-success">正常</span>';
			}}, 			
			{ label: '创建时间', name: 'createTime', index: 'create_time', width: 100 }			
        ],
		viewrecords: true,
        height: (pageInfo().height-130),
        rowNum: 15,
        rowList : [15,50,99],
        loadtext : loadGif,
        rownumbers: true, 
        rownumWidth: 25, 
        autowidth:true,
        multiselect: true,
        pager: "#jqGridPager",
        loadComplete : function(data){
            if(data.code == 0){
                return data;
            }else if(data.code == 205){
                invalidAccess();
            }else{
                layer.alert(data.msg);
            }
        },
        jsonReader : {
            root: "page.list",
            page: "page.currPage",
            total: "page.totalPage",
            records: "page.totalCount"
        },
        prmNames : {
            page:"page", 
            rows:"limit", 
            order: "order"
        },
        gridComplete:function(){
        	//隐藏grid底部滚动条
        	$("#jqGrid").closest(".ui-jqgrid-bdiv").css({ "overflow-x" : "hidden" }); 
        }
    });

    thisPage = {
        initDom : function(){
            this.getTypeIdentity();
        },
        getAreaData : function(pid,containerDom,selectDom,labelText){
            selectArea.getData(baseURL + 'sysarea/getListArea',pid,containerDom,selectDom,labelText);
        },
        /**基地类型*/
        getTypeIdentity : function(){
            ajaxQuery(baseURL + 'subject/getTypeIdentity',{},function(data){
                setDataSelect('选择基地类型','#identity_id',data.data,'value','text');
            });
        }
    }
    thisPage.initDom();
});


var vm = new Vue({
	el:'#witapp',
	data:{
		showList: true,
		title: null,
		subject: {},
		q:{
            key: null
        }
	},
	methods: {
		query: function () {
			vm.reload();
		},
        addSubject: function(){
            this.openDialog();
        },
        editSubject : function(){
            var dataId = getSelectedRow();
            if(dataId == null){
                return ;
            }
            var _this = this;
            ajaxQuery(baseURL + "subject/queryMap/"+dataId,{},function(data){
                if(data.code == 0){
                    _this.openDialog(dataId,data.data);
                }else{
                    alert(data.msg);
                }
            });
        },
        openDialog : function(kid,map){
            var url = 'subject/save';
            var title = '添加经营主体';
            if(kid != null && kid.length >0){
                url = 'subject/update?data_id='+kid;
                title = '编辑经营主体';
            }
            $('#framImages').val('');//清空企业图片
            var loginUser = sessionStorage.getItem("loginUser");
            if(loginUser == 'admin'){
                $('#div_subject_username').css({"display":""});
            }else{
                $('#div_subject_username').css({"display":"none"});
            }
            addOrEdit(title,'#div_subject_dialog',['600px','520px'],function(indexLayero,layero){
                var user_name = $('#user_name').val();
                var name = $('#name').val();
                var identity_id = $('#identity_id').val();
                var identity_name = $('#identity_id').find("option:selected").text();
                var link_man = $('#link_man').val();
                var link_tel = $('#link_tel').val();
                var province_id = $('#farmProvinceId').val();
                var province_name = $('#farmProvinceId').find("option:selected").text();
                var city = $('#farmCityId').val();
                var city_name = $('#farmCityId').find("option:selected").text();
                var county = $('#farmCountyId').val();
                var county_name = $('#farmCountyId').find("option:selected").text();
                var villages = $('#farmTownsId').val();
                var villages_name = (villages != null && villages.length > 0) ? $('#farmTownsId').find("option:selected").text() : null;
                var hamlet = $('#farmVallageId').val();
                var hamlet_name = (hamlet != null && hamlet.length > 0) ? $('#farmVallageId').find("option:selected").text() : null;
                var framImages = $('#framImages').val();
                var status = $("input[name='status']:checked").val();
                if(loginUser == 'admin'){
                    if(user_name == null || user_name.length <= 0){
                        alert("请填写主体的登录账号");
                        return;
                    }
                }
                if(name == null || name.length <= 0){
                    alert("经营主体的名称必填项");
                    return;
                }
                if(identity_id == null || identity_id.length <= 0){
                    alert("请选择身份类型|主体类型");
                    return;
                }
                if(kid == null || kid.length <=0){
                    if(province_id == null || province_id.length <= 0){
                        alert("请选择省|市");
                        return;
                    }
                    if(city == null || city.length <= 0){
                        alert("请选择市|区");
                        return;
                    }
                    if(county == null || county.length <= 0){
                        alert("请选择区|县|市");
                        return;
                    }
                    if(villages == null || villages.length <= 0){
                        alert("请选择乡|镇|社区");
                        return;
                    }
                }
                if(link_man == null || link_man.length <= 0){
                    alert("联系人不能为空");
                    return;
                }
                if(link_tel == null || link_tel.length <= 0){
                    alert("联系电话不能为空");
                    return;
                }
                if(kid == null || kid.length <=0){
                    if(framImages == null || framImages.length <= 0){
                        alert("选择企业图片");
                        return;
                    }
                }
                var params = {
                    user_name : user_name,
                    name : name,
                    identity_id : identity_id,
                    identity_name : identity_name,
                    link_man : link_man,
                    link_tel : link_tel,
                    province_id : province_id,
                    province_name : province_name,
                    city : city,
                    city_name : city_name,
                    county : county,
                    county_name : county_name,
                    villages : villages,
                    villages_name : villages_name,
                    hamlet : hamlet,
                    hamlet_name : hamlet_name,
                    status : status
                }
                var formData = new FormData();
                for(var key in params){
                    formData.append(key,params[key]);
                }
                var files = document.getElementById("framImages").files;
                for(var index in files){
                    formData.append("image"+index,files[index]);
                }
                formHandle(url,formData,function(data){
                    if(0 == data.code){
                        layer.close(indexLayero);
                        vm.reload();
                    }else if(data.code == 198){
                        alert(data.msg,function(){
                            selfTopHref();
                        });
                    }else{
                        alert(data.msg);
                    }
                });
            });
            thisPage.getAreaData('0','#div_area_import','.clsProvince','选择省|市');
            if(kid != null && kid.length > 0){
                $("#user_name").attr("disabled","disabled");
                $("#showImages").css("display","");
                this.renderDom(map);
            }else{
                $("#showImages").css("display","none");
                $('#showImages').empty();
                $("#user_name").removeAttr('disabled');
            }
        },
        renderDom : function(map){
            for(var k in map){
                var v = map[k]+'';
                if(k == 'status'){
                    $("input[name='status'][value="+v+"]").attr("checked",true);
                }else if(k == 'pic'){
                    var html = "<div class=\"col-sm-12\">";
                    var graphic = v.split(',');
                    var first = graphic[0];
                    if(first == '/statics/images/default-face.png'){
                        html+='<div class="col-sm-2"></div>';
                        html+='<a class="col-sm-10" style="color:#459df5;" href="javascript:alert(\'尚未上传企业图片\');">企业图片</a>';
                    }else{
                        for (var i = 0; i<graphic.length; i++){
                            html+='<div class="col-sm-2"></div>';
                            html+='<a class="col-sm-10" style="color:#459df5;" title="点击查看企业图片" target="_blank" href="../..'+graphic[i]+'">企业图片'+(i+1)+'</a>';
                        }
                    }
                    html+="</div>";
                    $('#showImages').empty().append(html);
                }else{
                    $('#'+k).val(v);
                }
            }
        },
		add: function(){
			vm.showList = false;
			vm.title = "新增";
			vm.subject = {};
			vm.init();
		},
		update: function (event) {
			var dataId = getSelectedRow();
			if(dataId == null){
				return ;
			}
			vm.showList = false;
            vm.title = "修改";
            vm.init();
            vm.getInfo(dataId)
		},
		saveOrUpdate: function (event) {
			var url = vm.subject.dataId == null ? "subject/save" : "subject/update";
			$.ajax({
				type: "POST",
			    url: baseURL + url,
			    contentType: "application/json",
			    data: JSON.stringify(vm.subject),
			    success: function(r){
			    	if(r.code === 0){
						alert('操作成功', function(index){
							vm.reload();
						});
					}else{
						alert(r.msg);
					}
				}
			});
		},
		del: function (event) {
			var dataIds = getSelectedRows();
			if(dataIds == null){
				return ;
			}
            confirm('确定要删除选中的记录？', function(){
                ajaxExecute(baseURL + "subject/delete",JSON.stringify(dataIds),function(data){
                    if(data.code == 0){
                        $("#jqGrid").trigger("reloadGrid");
                    }else{
                        alert(data.msg);
                    }
                });
            });
		},
		getInfo: function(dataId){
			$.get(baseURL + "subject/info/"+dataId, function(r){
                vm.subject = r.subject;
                var html='';
                $('.graphics').empty().append(html);
                if(vm.subject.pic){
                    html='<a title="点击查看原图" target="_blank" href="../..'+vm.subject.pic+'"><img src="'+vm.subject.pic+'" style="height:530px;width:590px;border-radius:10px;"/></a>';
                	$('.graphics').empty().append(vm.subject.pic);
                }else{
                    html='<img src="/statics/images/default.png" class="img-box4">';
                }
                $('.graphics').empty().append(html);
            });
		},
		reload: function (event) {
			vm.showList = true;
			var page = $("#jqGrid").jqGrid('getGridParam','page');
			$("#jqGrid").jqGrid('setGridParam',{ 
				postData:{'key': vm.q.key},
                page:page
            }).trigger("reloadGrid");
		},
        init:function(){
        	$("#identity").bindSelect({
	            url: baseURL+"sys/item/getSelect/",
	            param: "46",
	            id: "itemId",
	            text: "name",
	            search: false,
	            change: null
	        });
        }
	}
});